from django.contrib.auth.decorators import login_required
from django.shortcuts import render,redirect,reverse
from django.http import HttpResponse
from .models import *
from .form import MappingForm
from computerstatus.models import *
import telnetlib
import time
import re
from jinja2 import Environment,FileSystemLoader
from pyecharts.globals import CurrentConfig
CurrentConfig.GLOBAL_ENV = Environment(loader=FileSystemLoader("./networkstatus/templates"))
from pyecharts import options as opts
from pyecharts.charts import Bar,Pie,WordCloud
from index.form import *
from django.contrib.auth.models import User
from django.contrib.auth import login, authenticate

# Create your views here.

# def InventorySheet(request):
#     # 创建用于生成表名的字段
#     table_name = "table_" + time.strftime('%Y-%m-%d_%H_%M', time.localtime())

# 网络接口实时获取函数
def TestNetwork():
    # 获取更新模块
    password = "PcFree2014"
    tip = "192.168.0.1"
    cmd = "show arp"
    confComplete = ""
    moreReg = '--More--'

    try:
        tn = telnetlib.Telnet(tip, port=23, timeout=50)
        tn.read_until(b"Password:")
        tn.write(password.encode('ascii') + b'\n')
        time.sleep(1)
    except Exception as e:
        print(e)
        return HttpResponse(e)

    tn.write(b'\n')
    tn.write(b'enable\n')
    tn.read_until(b'Password:')
    tn.write(password.encode('ascii') + b'\n')
    tn.write(cmd.encode('ascii') + b'\n')
    time.sleep(1)
    msg = tn.read_very_eager().decode('utf-8')
    moerFlag = re.search(moreReg, msg)
    confComplete = re.sub(moreReg, ' ', confComplete)
    confComplete = confComplete + msg

    while (moerFlag):
        tn.write(' '.encode('ascii'))
        time.sleep(0.2)
        msg = tn.read_very_eager().decode('utf-8')
        moerFlag = re.search(moreReg, msg)
        confComplete = re.sub(moreReg, ' ', confComplete)
        confComplete += msg

    tn.write('exit'.encode('ascii'))
    tn.close()

    # list1 为总的状态 list 类型
    # list2 为总条状态 ShowAddress 类型
    ccd = str(confComplete).split()
    list1 = []
    list2 = []
    num_in = []
    for x in range(0, len(ccd)):
        if ccd[x] == "Internet":
            for j in range(0, 6):
                if '\x08' in ccd[j + x]:
                    ccd[j + x] = " "
                if ccd[j + x] == "Internet" and j == 5:

                    num_in.append(" ")
                else:
                    num_in.append(ccd[j + x])
            list2.append(
                ShowAddress(protocol=num_in[0], address=num_in[1], min=num_in[2], ip_mac=num_in[3], ip_type=num_in[4],
                            interface=num_in[5]))
            list1.append(num_in)
            num_in = []

    # 每次调用该接口，都会写入一次数据库
    ShowAddress.objects.bulk_create(list2)
    return list1

# 显示网络接口类型
# 其他管理 - 网络状态(当前)
@login_required(login_url="login.html")
def UpNetwork(request):
    titleClass = "其他管理 - 网络状态(当前)"
    shu_num = 3
    ye_num = 11
    list1 = TestNetwork()

    listtab = ['协议类型','IP地址','延迟时间','MAC地址','类型','接口地址']

    return render(request,"tabshow.html",locals())


# list1 为总的状态
# list2 为一条状态
# 其他管理 - 在线统计
@login_required(login_url="login.html")
def StaNetwork(request):
    # 获取当前交换机数据
    # 更新所有关联表
    UpdateAll()
    titleClass = "其他管理 - 在线统计"
    shu_num = 3
    ye_num = 9
    list3 = TestNetwork()
    print(list3)

    # 比对IpAssets 表 和 ShowAddress 表中的数据，生成自动在线数据写入TestComputer表中，并返回当前数据给前端展示

    mactest = IpAssets.objects.values_list()
    test = "失败"
    ipTest = ""
    list2 = []
    list1 = []
    # print(list1)
    for i in mactest:
        # print(i[0],i[8])
        test_i = i[8].lower().replace(":","")
        if test_i:
            for j in list3:

                if j[3] == "Incomplete":
                    continue
                elif j[3].replace(".","") == test_i:
                    test = "自动测试成功"
                    ipTest = j[1]
                    break
        list2.append(
            TestComputer(it_number=i[1],seat_number=i[5],asset_users=i[6],mac_network=i[8],auto_test=test,c_network=ipTest))
        list1.append([i[1],i[5],i[6],i[8],test,ipTest])
        test = "失败"
        ipTest = ""
    
    TestComputer.objects.bulk_create(list2)

    listtab = ['资产编号','具体位置','资产使用者','MAC地址','提交方式','IP地址']

    return render(request,"tabshow.html",locals())

# 更新所有关联表
def UpdateAll():
    a = ComputerStatus.objects.filter(it_number__icontains="-").values('it_number', 'mac_network')

    for i in a:
        try:
            b = IpAssets.objects.get(ip_number=i['it_number'])
            b.ip_mac = i['mac_network']
            j = ComputerStatus.objects.get(it_number=i['it_number'])
            j.seat_number = b.ip_seat_number
            j.asset_users = b.ip_asset_users
            b.save()
            j.save()
        except Exception as e:
            print(e, i['it_number'])


# 其他管理 - 用户行为一览
@login_required(login_url="login.html")
def Behavior(request):
    infos = MappingForm(request.GET)
    shu_num = 3
    ye_num = 10
    titleClass = "其他管理 - 用户行为一览"
    list1 = NetworkLog.objects.values_list('time','site','mac','asset_users','seat_number','it_number','url_keyword')[:7]
    listtab = ['时间', '网址', 'MAC地址', '使用者', '具体位置', 'URL解析']

    return render(request,"firewallshow.html",locals())


# 词云生成
def Mapping(request):
    inkey = request.GET.get('s',"")
    listseah = request.GET.get('n',"")
    print(inkey,listseah)
    if inkey == None and listseah == None:
        list1 = NetworkLog.objects.filter(it_number='WP-DN-SH-210-2').values_list('site','it_number')
    elif listseah == 'it_number':
        list1 = NetworkLog.objects.filter(it_number=inkey).values_list('site','it_number')
    elif listseah == 'asset_users':
        list1 = NetworkLog.objects.filter(asset_users=inkey).values_list('site','it_number')
    dict = {}
    for i in list1:
        if i[0] in dict:
            dict[i[0]] += 1
        else:
            dict[i[0]] = 1

    name = list(dict.keys())
    value = list(dict.values())

    c = (

        WordCloud().add("词云",list(zip(name,value)))
        # Pie().add("Demo",[("a", 34), ("b", 82), ("c", 64), ("d", 45), ("e", 57)])
        # Bar().add_xaxis(['衬衫','羊毛衫','雪纺衫','裤子','高跟鞋','袜子'])
        # .add_yaxis("商家A",[5,20,36,10,75,90])
        # .add_yaxis("商家B",[15,25,16,55,48,8])
        .set_global_opts(title_opts=opts.TitleOpts(title="词云生成:"+listseah,subtitle=inkey))

    )
    return HttpResponse(c.render_embed())


def loginView(request):
    titleClass = "系统管理 - 登录"
    infos = LoginForm()
    if request.method == "POST":
        username = request.POST.get('username','')
        password = request.POST.get('password','')

        if User.objects.filter(username=username):

            user = authenticate(username=username,password=password)

            if user:
                login(request,user)
                return redirect(reverse("index:index"))

            else:
                print("登录失败")
    return render(request, "login.html",locals())